package git.luohao.datasource;

import com.alibaba.csp.sentinel.datasource.AutoRefreshDataSource;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.log.RecordLog;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DBRefreshableDatasource<T> extends AutoRefreshDataSource<String, T> {

    private static final Charset DEFAULT_CHAR_SET = Charset.forName("utf-8");
    private long lastModified;
    private JdbcTemplate jdbcTemplate;

    public DBRefreshableDatasource(JdbcTemplate jdbcTemplate, Converter<String, T> configParser) {
        this(jdbcTemplate, configParser, 3000L);
    }

    public DBRefreshableDatasource(JdbcTemplate jdbcTemplate, Converter<String, T> configParser, long recommendRefreshMs) {
        super(configParser, recommendRefreshMs);
        this.lastModified = 0L;
        this.jdbcTemplate = jdbcTemplate;
        this.lastModified = System.currentTimeMillis();
        System.out.println("=================我初始化啦=================");
        this.firstLoad();
    }

    private void firstLoad() {
        try {
            T newValue = this.loadConfig();
            this.getProperty().updateValue(newValue);
        } catch (Throwable var2) {
            RecordLog.info("loadConfig exception", var2);
        }

    }
    @Override
    public String readSource() throws Exception {
        String json = null;
        String sql = "select limit_flow from tb_ai_routedefinition where 1 = 1;";
        final List<String> list = this.jdbcTemplate.queryForList(sql, String.class);
        List<Object> jsonObjectList = new ArrayList<>();
        for (String s : list) {
            final JSONArray array = JSONObject.parseArray(s);
            List<Object> objectList = JSONArray.parseArray(array.toJSONString());
            jsonObjectList.addAll(objectList);
        }
        json = JSON.toJSONString(jsonObjectList);
        System.out.println(json);

        return json;
    }

    protected boolean isModified() {
        long curLastModified = System.currentTimeMillis();
        System.out.println("判断是否修改了");
        if (curLastModified != this.lastModified) {
            this.lastModified = curLastModified;
            return true;
        } else {
            return false;
        }
    }

    public void close() throws Exception {
        super.close();
    }
}
